package com.jintu.portal.utils;

import com.jintu.portal.constant.BaseConstant;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by liyou on 2017/9/5.
 */
public class SessionUtil {

    public static void setRequest(String name, Object value) {
        getRequest().setAttribute(name, value);
    }

    public static <T> T getRequest(String name, Class<T> clz) {
        Object obj = getRequest().getAttribute(name);
        return obj == null ? null : (T) obj;
    }

    public static void setSession(String name, Object value) {
        getRequest().getSession().setAttribute(name, value);
    }

    public static <T> T getSession(String name, Class<T> clz) {
        Object obj = getRequest().getSession().getAttribute(name);
        return obj == null ? null : (T) obj;
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static String getCookieByName(String name) {
        Cookie[] cookies = getRequest().getCookies();
        if(cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    public static String restReqBody() {
        return getRequest(BaseConstant.REST_REQ_BODY_KEY, String.class);
    }

    public static String restRespBody() {
        return getRequest(BaseConstant.REST_RESP_BODY_KEY, String.class);
    }
}
